<?php
 
namespace Piwik\Plugins\AdsPlace;


use Exception;
use Piwik\Common;
use Piwik\API\Request;
use Piwik\Date;
use Piwik\Piwik;
use Piwik\Tracker\Cache;
use Piwik\Plugins\AdsPlace\Lib\Apitools;
use Piwik\Plugins\AdsPlace\Lib\RedisAdapter;
use Piwik\Settings\Storage\Backend\PluginSettingsTable;
use Piwik\Plugins\AdsPlace\ExtendAPI;
use Piwik\Plugins\AdsPlace\Lib\UploadFiles;
use Piwik\Url;

class API extends \Piwik\Plugin\API
{
    private $model;
    public $result;
    /**
     * 构造函数
     * 把model传过来
     */
    public function __construct(Model $model) {
        $this->model = $model;
        $this->result = array(
            'status'=>0,
            'data'=>[],
            'msg'=>''
        );
    } 
    /***
     * 用这个方法扩展到DispatchAPI里面的具体method方法。
     */
    public function dispatch( $enews='getMedias')
    {       
        $dispatch = new ExtendAPI( $this->model) ;
        if(is_callable([$dispatch, $enews])){
           try{
               
              return  call_user_func_array([ $dispatch , $enews], []);
                
           } catch (Exception $ex) {
               throw  $ex;
           } 
           
        }else{
            return  call_user_func_array([$this, $enews],[]);
        }
    }
    /**
     * 这个是 万能魔术方法，访问不存在的method会执行它
     * @param type $name
     * @param type $arguments
     * @return type
     */
    public function __call($name, $arguments=[]) {
        return  " method  (  $name  ) is not exist ";
    }

    /**
     * 
     * @throws Exception
     */
    public function saveLybrowerJson()
    {
       Piwik::checkUserIsNotAnonymous();
       $pluginSettings =   new PluginSettingsTable('Lybrowerjson',   'xfplay');
       //$settings = $pluginSettings->load();
      
       //保存到redis
       $key     =  Common::getRequestVar('cacheId', 'lybrower-ios-adverte-setting');
       $redis   =  Common::getRequestVar('redisStr','127.0.0.1@6379');
       $adapter  =  new RedisAdapter(  );
       $settings = $adapter->formatLybrowerJson();
      
       try{
            $adapter->connectReis($redis); 
            $adapter->set($key, json_encode($settings));
            
       } catch (Exception $ex) {
           throw  $ex;
       }
        
       $pluginSettings->save(['json' => $settings,  'cacheId'=> $key,'redisStr'=> $redis ]);      
    }
    /**
     * 获取配置参数信息
     * @return type
     */
    public function getLybrowerjson()
    {
        Piwik::checkUserIsNotAnonymous();
        $pluginSettings =   new PluginSettingsTable('Lybrowerjson', 'xfplay');
        $settings = $pluginSettings->load();
        return $settings ;
    }
    /**
     * 把 影音先锋 广告 配置参数记录到json 文件
     */
    public function xfjsonSave()
    {
       Piwik::checkUserIsNotAnonymous();
       $pluginSettings =   new PluginSettingsTable('xfjson',   'xfplay');
       //$settings = $pluginSettings->load();
       
       //保存到redis
       $key     =  Common::getRequestVar('cacheId', "xfjson-app-adverte-setting");
       $redis   =  Common::getRequestVar('redisStr','127.0.0.1@6379');
       $adapter  =  new RedisAdapter(  );
       $settings = $adapter->formatXfjson();
       
       try{           
            $adapter->connectReis($redis);            
            $adapter->set($key, json_encode($settings  ));
            
       } catch (Exception $ex) {
           throw  $ex;
       }
        
       $pluginSettings->save([ 'json' => $settings,  'cacheId'=> $key,'redisStr'=> $redis ]);     
       
    }
    /**
     * 获取配置参数信息
     * @return type
     */
    public function xfjsonGet()
    {
        Piwik::checkUserIsNotAnonymous();
        $pluginSettings =   new PluginSettingsTable('xfjson', 'xfplay');
        $settings = $pluginSettings->load();
        return $settings ;
    }
    /**
     * 把配置参数按plugin 指定的savekeys 保存起来；
     * @return type
     */
    public function xfdetection()
    {
        Piwik::checkUserIsNotAnonymous();
        $plugin = Common::getRequestVar('plugin','');
        $savekeys = Common::getRequestVar('savekeys','');
        if(empty($plugin)){
            return ;
        }
        $pluginSettings =   new PluginSettingsTable( $plugin,  Piwik::getCurrentUserLogin());
        $save = [];
        if(!empty($savekeys)){
            $fields = explode(",", $savekeys);
            foreach($fields as $field){
                $save[$field] = Common::getRequestVar( $field,'');
            }
        }
        if(!empty($save)){
            $pluginSettings->save( $save);  
        }        
    }
    public function xfdetectionGet(){
        Piwik::checkUserIsNotAnonymous();
        $userLogin = Piwik::getCurrentUserLogin();
        $p1 =   new PluginSettingsTable('redis_detection' , $userLogin);
        $r['redis_detection'] = $p1->load();
        
        $p2 =   new PluginSettingsTable('mysql_detection' , $userLogin);
        $r['mysql_detection'] = $p2->load();
        
        $p3 =   new PluginSettingsTable('pgsql_detection' , $userLogin);
        $r['pgsql_detection'] = $p3->load();
        
        return $r;
    }

    /**
     * 更新站点的 meta信息
     * @param type $idSite
     * @param type $meta
     * @return type
     */

    public function updateSiteMeta( $idSite, $meta= [])
    {
        Piwik::checkUserIsNotAnonymous();
        // 传递meta 的json 格式字符串        
       $meta = json_encode($meta);
       $this->model->updateSiteMeta($idSite, $meta);
       $this->result['data'] = $idSite;
       $this->result['msg'] = '保存站点信息成功';
       return $this->result;
    }
    //    获取所有站点数据
    public function getAllSites()
    { 
        $sites  = $this->model->getAllSites();
        $return = array();
        foreach ($sites as $site) {
        //  $this->enrichSite($site);
            $return[$site['idsite']] = $site;
        }

        return \Piwik\Site::setSitesFromArray($return);
         
    }
    private function _place_post_data()
    {
        
    }

    /**
     * 添加广告位数据到数据库
     *  $data = [ id , title, caculate ,perPrice ,adtype, adsize, sizebill, contains, tags]
     * @param type $data
     * @return type
     */
    public function  createPlace( $placeName,
                                    $costType = '1',
                                    $perPrice= '0',
                                    $adtype= '1',
                                    $sizeDot= '',
                                    $placeType= '1',
                                    $adtags= '',
                                    $zhekou= '0',
                                    $placeHeight= '0',
                                    $placeWidth= '0' , $orderid=0,$ownerid=0 ) 
    {
         Piwik::checkUserIsNotAnonymous();
        $data = [
            'placeName' =>      $placeName,
            'costType'  =>      $costType,
            'perPrice'  =>      $perPrice,
            'adtype'    =>      $adtype,
            'sizeDot'   =>      $sizeDot,
            'placeType' =>      $placeType,
            'adtags'    =>      $adtags,
            'zhekou'    =>      $zhekou,
            'placeHeight'   =>  $placeHeight,
            'placeWidth'    =>  $placeWidth,
            'disabled'  =>  0,
            'filt'      =>  0, //填充广告数
            'orderid'   => $orderid,
              'ownerid'=> $ownerid,
    //   'createtime' =>  Date::now()->getDatetime(),
    //   'modifytime' =>  Date::now()->getDatetime(),
        ];
         $data['creator_login'] = Piwik::getCurrentUserLogin();
        $id = $this->model->insertAdPlace($data);
        
        return ['value'=> $id, 'msg'=> '添加成功', 'errorCode'=>0];
    }
    /**
     * 更新 广告位
     * @param type $id
     * @param type $placeName 广告位名称
     * @param type $costType  计费方式
     * @param type $perPrice 计费价格
     * @param type $adtype  平台类型
     * @param type $sizeDot  尺寸 比例 "*" 或者 ":"
     * @param type $placeType 广告位类型
     * @param type $adtags 标签
     * @param type $zhekou  折扣比例
     * @param type $placeHeight 尺寸高度
     * @param type $placeWidth  尺寸宽
     * @return type
     */
    public function updatePlace($id,
                                    $placeName,
                                    $costType = '1',
                                    $perPrice= '0',
                                    $adtype= '1',
                                    $sizeDot= '',
                                    $placeType= '1',
                                    $adtags= '',
                                    $zhekou= '0',
                                    $placeHeight= '0',
                                    $placeWidth= '0', $orderid=0 , $ownerid=0 ){
       Piwik::checkUserIsNotAnonymous();  
         $data = [
            'placeName' =>      $placeName,
            'costType'  =>      $costType,
            'perPrice'  =>      $perPrice,
            'adtype'    =>      $adtype,
            'sizeDot'   =>      $sizeDot,
            'placeType' =>      $placeType,
            'adtags'    =>      $adtags,
            'zhekou'    =>      $zhekou,
            'placeHeight'   =>  $placeHeight,
            'placeWidth'    =>  $placeWidth,   
            'orderid'     => $orderid,
             'ownerid'=> $ownerid,
            'modifytime' =>  Date::now()->getDatetime(),
        ];  
          $data['creator_login'] = Piwik::getCurrentUserLogin();
        $this->model->updatePlace($id, $data);
        
        return ['value'=> $id, 'msg'=> '修改广告位成功', 'errorCode'=>0]; 
    }
    /*
    * 获取广告位的列表
    */ 
    public function getAllsPlace($page=1, $pageSize=10, $segment = '')
    {
        $page = max($page, 1);    
        $offset  = ($page -1 ) * $pageSize;
        $where = ''; 
        $bind = [];
          //根据指定的ids 字符串获取；
        if(isset($segment['ids']) ){            
            $ids = trim($segment['ids'],',' );            
            if(!empty($ids)){               
                $where.= "AND id IN  ( $ids )  ";
            }else{
                //避免查询出其他数据
                $where.= "AND id IN  ( 0 )  ";
            }
        }
        
        if(isset($segment['keyword'])  && !empty($segment['keyword']) ){
            if(is_numeric($segment['keyword'])){
                $where.= "AND id = ? ";
                $bind['id'] =  intval( trim($segment['keyword']))  ;   
            }else{
                $where.= "AND placeName LIKE ? ";
                $bind['placeName'] =  '%'.trim($segment['keyword']) .'%';
            }
        }
        // 广告平台 pc 移动网页  App
        if(isset($segment['adtype'])  && !empty($segment['adtype'])){
            $where.= "AND  adtype = ?  ";
            $bind['adtype'] = $segment['adtype'];
        }
        //类型 嵌入 悬浮 视频贴片 placeType
        if(isset($segment['placeType'])  && !empty($segment['placeType'])){
            $where.= "AND  placeType = ?  ";
            $bind['placeType'] = $segment['placeType'];
        }
        // 状态 禁用 停用 启用 status
        if(isset($segment['status'])  && !empty($segment['status'])){
            $disabeld = intval($segment['status']);
            $where.= "AND  disabled = ?  ";
            // 默认0 = 启用，转换一下 2 为 0时状态；
            $bind['disabled'] =  $disabeld;// == '2' ? 0 : $disabeld;
        } 
        //标签
         if(isset($segment['adtags'])  && !empty($segment['adtags']) ){
            
                $where.= "AND adtags LIKE ? ";
                $bind['adtags'] =  '%'.trim($segment['adtags']) .'%';
            
        }
        //加入当前用户只显示当前用户的
         $where.= "AND  creator_login = ?  ";
         $bind['creator_login'] = Piwik::getCurrentUserLogin();
        //
        if(strlen($where)>0){
            $where = " WHERE ". trim($where , 'AND');
        }
        
        $ret =  $this->model->getAllsPlace($offset, $pageSize, $where, $bind);
       
       return $ret;
    }
    /**
     * 改变状态 disabled的值
     * @param type $idPlaces
     * @param type $disabled
     */
    public function changeDisableStatus($idPlaces, $disabled)
    {
        Piwik::checkUserIsNotAnonymous();
        return $this->model->updateDisabled($idPlaces, $disabled);
    }
    /**
     * 获取一条广告位信息
     * @param type $idPlace = id 值
     * @return type
     */
    public function getOnePlace($idPlace) 
    {
        return $this->model->getOnePlace($idPlace);
    }
    // 删除一个广告位
    public function deletePlace($idPlace) 
    {
        Piwik::checkUserIsNotAnonymous();
        $this->model->deletePlace($idPlace);
        return ['errorCode'=>0, 'msg'=> '删除广告位成功'];
    }
    
    //新增一个 adverte 广告数据
    /**
     * `adverteName`    `caculateMethod`    `perPrice`    `adtype` 			
            `placeIds` 	   `topLimitNum`   `dayLimitNum`   `frequencyNum`    `rangeMethod` 	
            `rangeNum` 	   `proid`  `startday`	  `starttime`  `hasendtime`  `endday` 			
            `endtime` 	  `proidRows`	   `limitArea`	  `regions`	   `createtime`		
            `modifytime`    `disabled` 	  `status` 	
    */
   private function _foramt_adverte(){
        $data['adverteName'] = Common::getRequestVar('adverteName','');
        $data['caculateMethod'] = Common::getRequestVar('caculateMethod','1');
        $data['perPrice'] = Common::getRequestVar('perPrice','');
        $data['adtype'] = Common::getRequestVar('adtype','1');
        $data['placeIds'] = Common::getRequestVar('placeIds','');
        $data['topLimitNum'] = Common::getRequestVar('topLimitNum','0');
        $data['dayLimitNum'] = Common::getRequestVar('dayLimitNum','0');
        $data['frequencyNum'] = Common::getRequestVar('frequencyNum','0');
        $data['rangeMethod'] = Common::getRequestVar('rangeMethod','1');
        $data['rangeNum'] = Common::getRequestVar('rangeNum','0');
        $data['proid'] = Common::getRequestVar('proid','1');
        $data['startday'] = Common::getRequestVar('startday','');
        $data['starttime'] = Common::getRequestVar('starttime','');
        $data['hasendtime'] = Common::getRequestVar('hasendtime','0');
        $data['endday'] = Common::getRequestVar('endday','');
        $data['endtime'] = Common::getRequestVar('endtime','');
        $data['proidRows'] = Common::getRequestVar('proidRows','');
        $data['limitArea'] = Common::getRequestVar('limitArea','');
        $data['regions'] = Common::getRequestVar('regions','');
        $data['priority'] =  Common::getRequestVar('priority','') ;
        $data['priorityLeve'] =  Common::getRequestVar('priorityLeve','') ;
        $data['weight'] =  Common::getRequestVar('weight','') == "true" ? 1: 0;
        $data['weightLeve'] =  Common::getRequestVar('weightLeve','') ;
        if( $data['weight'] ==0 ){
            $data['weightLeve'] = 0;
        }
         $data['creator_login'] = Piwik::getCurrentUserLogin();
        $data['medias'] =  Common::getRequestVar('medias','') ;
        array_filter($data, function( $val){
                return trim($val);
        });
       //把物料的类型 保存，提供搜索方便
        if(!empty($data['medias'])){
            $data['mediastype'] =  $this->model->getMediasTypes($data['medias']);
        }   
        return $data;
   }
    public function createAdverte(   )
    {
         Piwik::checkUserIsNotAnonymous();
        $data = $this->_foramt_adverte();
        $data['disabled'] = 0;
        $data['status'] = 1;  
       
        
        $id = $this->model->insertAdverte($data);
        
        return ['value'=> $id, 'msg'=> '添加成功', 'errorCode'=>0];
    }
    //  更改一个广告 内容
    public function updateAdverte()
    {
         Piwik::checkUserIsNotAnonymous();
        $data = $this->_foramt_adverte();
        $id = Common::getRequestVar('id','0');
     
        $this->model->updateAdverte($id, $data);
        
         return ['value'=> $id, 'msg'=> '更新成功', 'errorCode'=>0];
    }
       // 删除一个广告位
    public function deleteAdverte($idadverte) 
    {
         Piwik::checkUserIsNotAnonymous();
        $this->model->deleteAdverte($idadverte);
        return ['errorCode'=>0, 'msg'=> '删除广告投放成功'];
    }
    //获取广告列表
    public function getAllsAdvertes($page=1, $pageSize=10, $segment = '')
    {
        $page = max($page, 1);    
        $offset  = ($page -1 ) * $pageSize;
        $where = ''; 
        $bind = [];
        
        // 按 placeIds  搜索
        if(isset($segment['idplace'])  && !empty($segment['idplace']) ){
            $where.= "AND concat(',',`placeIds`,',') LIKE ? ";
            $bind['idplace'] =  '%,'.trim($segment['idplace']) .',%';
        } 
       //按关键词搜索
        if(isset($segment['keyword'])  && !empty($segment['keyword']) ){
            $where.= "AND adverteName LIKE ? ";
            $bind['adverteName'] =  '%'.trim($segment['keyword']) .'%';
        }
        // 广告平台 pc 移动网页  App
        if(isset($segment['adtype'])  && !empty($segment['adtype'])){
            $where.= "AND  adtype = ?  ";
            $bind['adtype'] = $segment['adtype'];
        }
        //类型 嵌入 悬浮 视频贴片 placeType
        if(isset($segment['caculateMethod'])  && !empty($segment['caculateMethod'])){
            $where.= "AND  caculateMethod = ?  ";
            $bind['caculateMethod'] = $segment['caculateMethod'];
        }
        // 状态 禁用 停用 启用 status
        if(isset($segment['status'])  && !empty($segment['status'])){
            $disabeld = intval($segment['status']);
            $where.= "AND  status = ?  ";
            // 默认0 = 启用，转换一下 2 为 0时状态；
            $bind['status'] =  $disabeld ;//== '2' ? 0 : $disabeld;
        } 
        //搜索 物料类型
        if(isset($segment['medias'])  && !empty($segment['medias']) ){
            $type = ['','txt','image','flash','html','video'];
            $keyword = $type[$segment['medias']];
            if(!empty($keyword)){
                $where.= "AND concat(',',`mediastype`,',') LIKE ? ";
                $bind['mediastype'] =  '%,'.trim( $keyword ) .',%';
            }
        } 
        //搜索时间范围
        if(isset($segment['timelimit']) && !empty($segment['timelimit']) &&
              $segment['timelimit']!= 'null'  ){
            $worktime = $segment['worktime'];
            
            $timelimit = explode(",", $segment['timelimit']);
            
            if($worktime==2 && !empty($timelimit[0])){
                $where.= "AND  (startday  BETWEEN  ?  AND  ?)  and    ( endday > ? ) ";
                $bind['startday0'] =  $timelimit[0];
                $bind['startday1'] =  $timelimit[1];  
                //
                
                $bind['endday1'] =  $timelimit[1];
                //不搜索 结束时间
            }elseif($worktime==1  && !empty($timelimit[0])){               
                 $where.= "AND  ( startday  BETWEEN  ?  AND  ? )";
                 $bind['startday0'] =  $timelimit[0];
                 $bind['startday1'] =  $timelimit[1];            
            
            }
            
        }
          //加入当前用户只显示当前用户的
         $where.= "AND  creator_login = ?  ";
         $bind['creator_login'] = Piwik::getCurrentUserLogin();
        if(strlen($where)>0){
            $where = " WHERE ". trim($where , 'AND');
        }
        
        $ret =  $this->model->getAllsAdvertes($offset, $pageSize, $where, $bind);
  
        //获取列表当前全部代码位      
        $needupdate = [];
        foreach($ret['data']  as $key => $val){
            $ret['data'][$key]['placeIdsArr'] = [];
            $ret['data'][$key]['mediasArr'] = [];
          // 获取每条记录对应的 代码位信息
            $ret['data'][$key]['placeStatus'] = 0;
            if($val['placeIds']){
                $tmp = explode(',',$val['placeIds']);              
                foreach( $tmp as $k=> $v){
                    if($ret['places'][$v]){
                         $ret['data'][$key]['placeIdsArr'][$v] = $ret['places'][$v];
                         //判断投放方案所在的广告位的开启状态                         
                        //  1=删除 2=启用 3=停用,当前方案投放的广告位只要有启用的 ，投放方案状态算启用。
                         $ret['data'][$key]['placeStatus'] = ($ret['places'][$v]['disabled']==2 ? 1: 0) || $ret['data'][$key]['placeStatus'];
                    }
                } 
            }
            /*计算广告投放方案的状态1=待投放 2=正在投放 3= 暂停 9 =结束投放 
             * 判断 投放时间结束表示投放结束，
             * 投放时间未开始=待投放，处于投放时间中，
             * 判断广告位placeStatus 的状态true，false */
            $ret['data'][$key]['runstatus'] = 1; //初始值表示待投放；
            if( $ret['data'][$key]['proid']==2){ //按时间段投放
                $nowstr = date('Y-m-d');
                if(!empty($ret['data'][$key]['proidRows'])){
                    if(strpos(','.$ret['data'][$key]['proidRows'].',', $nowstr) !== FALSE ){
                        $ret['data'][$key]['runstatus'] = 2;
                    }
                }
            }else{ /*设置过开始时间或者结束时间*/
                   $now = time();
                if (strtotime($ret['data'][$key]['startday'] . ' ' . $ret['data'][$key]['starttime']) < $now) {
                    $ret['data'][$key]['runstatus'] = 2;
                }
                //设置了到期时间的，到期判断
                if ($ret['data'][$key]['hasendtime'] && ( strtotime($ret['data'][$key]['endday'] . ' ' . $ret['data'][$key]['endtime']) < $now)) {
                    $ret['data'][$key]['runstatus'] = 9;
                    //投放结束
                }
            }
            // 如果当前的广告位 未启用
            if(  $ret['data'][$key]['runstatus'] ==2 ){
                if($ret['data'][$key]['placeStatus'] == 0){
                    $ret['data'][$key]['runstatus'] = 3 ;// 暂停投放状态。
                }
            }
            if($ret['data'][$key]['runstatus'] != $ret['data'][$key]['status']){
                $ret['data'][$key]['status'] = $ret['data'][$key]['runstatus'];
                $needupdate[$ret['data'][$key]['id']] = " WHEN " .$ret['data'][$key]['id'] ." THEN ". $ret['data'][$key]['status'];
            }
            /*投放状态 技术结束*/
             //获取每条记录 对应的 物料 信息
            if($val['medias']){
                $tmp = explode(',',$val['medias']);              
                foreach( $tmp as $k=> $v){
                    if($ret['medias'][$v]){
                         $ret['data'][$key]['mediasArr'][$v] = $ret['medias'][$v];
                    }
                }  
            }
        }
        /*更新状态*/
        if(!empty($needupdate)){
            $sql = "";
            $dot = "";
            $ids = [];
            foreach ($needupdate as $key => $v ){
                $sql.= $dot . $v;
                $dot = " ";
                array_push($ids, $key);
            }
            $sql = " update ".Common::prefixTable('adverte'). " SET status = CASE id $sql END  where id in (".implode(",", $ids).")";
            $this->model->query($sql);
        }
       
       return $ret;     
    }
    /**
     * 返回 广告物料 数据表字段内容；
     * @return type
     */
    private function _foramt_medias(){
        $data['name'] = Common::getRequestVar('name','');
        $data['type'] = Common::getRequestVar('type','');
       // $data['txt'] = Common::getRequestVar('txt','');
        $data['target'] = Common::getRequestVar('target','1');
        $data['linkurl'] = Common::getRequestVar('linkurl','');
        $data['trackurl'] = Common::getRequestVar('trackurl','');
        $data['width'] = Common::getRequestVar('width','0');
        $data['height'] = Common::getRequestVar('height','0');
        $data['alt'] = Common::getRequestVar('alt','');
        $data['attachments'] = Common::getRequestVar('attachments','');
        $data['flashbg'] = Common::getRequestVar('flashbg','0');
        $data['flashpic'] = Common::getRequestVar('flashpic','');
        $data['flashpicwidth'] = Common::getRequestVar('flashpicwidth','0');
        $data['flashpicheight'] = Common::getRequestVar('flashpicheight','0');
        $data['videotimeline'] = Common::getRequestVar('videotimeline','0');
        $data['trackClick'] = Common::getRequestVar('trackClick','0');
        //$data['disabled'] = Common::getRequestVar('disabled','0');
        $data['creator_login'] = Piwik::getCurrentUserLogin();
        array_filter($data, function( $val){
                return trim($val);
        });
//        文字广告
        if($data['type'] === 'txt'){
            $data['content'] = json_encode([
                'type'=> $data['type'],
                'txt'=> Common::getRequestVar('txt',''),
                'style'=> Common::getRequestVar('contentStyle',''),
                'activeStyle'=> Common::getRequestVar('activeStyle',''),
            ]);
        }
        if($data['type'] === 'image'){
             $data['content'] = json_encode([
                'type'=> $data['type'],
                'image'=> Common::getRequestVar('image',''),
           
            ]);
        }
         if($data['type'] === 'html'){
             /*cntype 区别采用哪种模板*/
             $data['cntype'] = Common::getRequestVar('cntype','1');
             $content = Common::getRequestVar('content','');
             $content['type'] = $data['type'];
             $data['content'] = json_encode( $content);
        }
         if($data['type'] === 'flash'){
             $data['content'] = json_encode([
                'type'=> $data['type'],
                'flash'=> Common::getRequestVar('flash',''),
           
            ]);            
        }
         if($data['type'] === 'video'){
             $data['content'] = json_encode([
                'type'=> $data['type'],
                'video'=> Common::getRequestVar('video',''),
           
            ]);            
        }
        // 信息流广告
        if($data['type'] === 'stream'){
              $data['cntype'] = Common::getRequestVar('cntype','1');
              $cn =  Common::getRequestVar('cn','');
              $cn['type'] = $data['type'];
              $cn['cntype'] =  $data['cntype'];
              $data['content'] = json_encode( $cn);
          }
        
        return $data;
   }
   /**
    * 增加媒体物料 数据表记录
    * @return type
    */
    public function createMedias(   )
    {
        Piwik::checkUserIsNotAnonymous();
        $data = $this->_foramt_medias();
        $data['disabled'] = 0;       
       
        $id = $this->model->insertMedias($data);
        
        return ['value'=> $id, 'msg'=> '添加成功', 'errorCode'=>0];
    }
    //  更改一个物料 内容
    public function updateMedias()
    {
         Piwik::checkUserIsNotAnonymous();
        $data = $this->_foramt_medias();
        $id = Common::getRequestVar('id','0');
        if($id){
            
            $this->model->updateMedias($id, $data);
        }
        
        return ['value'=> $id, 'msg'=> '更新成功', 'errorCode'=>0];
    } 
           // 删除一个广告物料
    public function deleteMedias($idmedias) 
    {
         Piwik::checkUserIsNotAnonymous();
        $this->model->deleteMedias($idmedias);
        return ['errorCode'=>0, 'msg'=> '删除物料成功'];
    }
    /**
     * 获取素材列表 
     * @return type
     */
    public function getAllMedias($page=1, $pageSize=10, $segment = '')
    {
        $page = max($page, 1);    
        $offset  = ($page -1 ) * $pageSize;
        $where = '';
        $bind = [];
        //根据指定的ids 字符串获取；
        if(isset($segment['ids']) ){            
            $ids = trim($segment['ids'],',' );            
            if(!empty($ids)){               
                $where.= "AND id IN  ( $ids )  ";
            }else{
                //避免查询出其他数据
                $where.= "AND id IN  ( 0 )  ";
            }
        }
        if(isset($segment['keyword'])  && !empty($segment['keyword']) ){
            if(is_numeric($segment['keyword'])){
                $where.= "AND  id =  ? ";
                $bind['id'] =   intval (trim($segment['keyword'])) ;
            }else{
                $where.= "AND  name LIKE ? ";
                $bind['name'] =  '%'.trim($segment['keyword']) .'%';
            }
        }
        // 物料类型 txt flash html image video  
        if(isset($segment['medias'])  && !empty($segment['medias'])){
            $where.= "AND  type = ?  ";
            $bind['type'] = $segment['medias'];
        }
        // 物料状态 status 
        if(isset($segment['status'])  && !empty($segment['status'])){
            $status = ( $segment['status'] ==1)? 0: 1;
            $where.= "AND  disabled = ?  ";
            $bind['disabled'] = $status;
        }
//        搜索宽高
         if(isset($segment['wh'])  && !empty($segment['wh'])){
            if(strpos($segment['wh'], '*')){
                $wh =  explode('*', $segment['wh']);
                $where.= "AND   width = ?   AND  height= ?  ";
                $bind['width'] = intval(trim($wh[0]));           
                $bind['height'] = intval(trim($wh[1]));
            }else{
                //只有一个数字时搜索 width or height
                $where.= "AND  ( width = ? OR height = ? )";
                $bind['width'] = intval( trim($segment['wh'])); 
                $bind['height'] = intval(trim($segment['wh']));
            }     
        }
         //加入当前用户只显示当前用户的
         $where.= "AND  creator_login = ?  ";
         $bind['creator_login'] = Piwik::getCurrentUserLogin();
        if(strlen($where)>0){
            $where = " WHERE ". trim($where , 'AND');
        } 
        
        $ret =  $this->model->getAllMedias($offset, $pageSize, $where, $bind);
        foreach($ret['data'] as $key=>$val){
            $ret['data'][$key]['content'] =  json_decode($val['content'],true);
        }
       
        return $ret; 
    }

    public function transfile(  )
    {
        //加入此autoload 加载本插件 里面的vendor 库，主要是 gzzhttp；
        require PIWIK_INCLUDE_PATH.'/plugins/AdsPlace/vendor/autoload.php';      
        // 用gzzhttp库 上传文件到 接口 同密电附件服务器一致；
       $api = new Apitools();  
      
       $transfile = $_FILES['file'] ;
       
       $extension  =  pathinfo( $transfile['name'], PATHINFO_EXTENSION) ;
       $tmpFilePath = $transfile['tmp_name'];
       $originalName = $transfile['name'];
       /*采用thinkphp-image组件 上传到当前站点 的plugins/AdsPlace/uploads目录保存图片*/
       $upload = new  UploadFiles();
       $siteurl  = Url::getCurrentUrlWithoutFileName();
       $saveName = time(). rand(1, 100).".{$extension}";
       $savedir = "plugins/AdsPlace/uploads/".date('Ym')."/";
       $dirs = explode("/", $savedir);
       $basedir = PIWIK_INCLUDE_PATH;
       foreach($dirs as  $dir){
           if($dir && !is_dir( $basedir. DIRECTORY_SEPARATOR. $dir)){
                 mkdir( $basedir. DIRECTORY_SEPARATOR. $dir);
           }
           $basedir = $basedir . DIRECTORY_SEPARATOR. $dir ;           
       }
       $fileUrl = $siteurl.$savedir. $saveName;
       $distPath =  PIWIK_INCLUDE_PATH.DIRECTORY_SEPARATOR. $savedir. $saveName;
       $upload->transfer($tmpFilePath,$distPath);
       $data['data'] = $fileUrl;
       $data['originalName'] = $originalName;
       $data['result'] = 'success';
       $data['error'] = ['errorCode'=>0, 'msg'=> '上传成功'];
       return $data;
       /*上面部分采用 图片保存在本站点 的目录，下面部分是可以对接 公司的minio 系统
       
       $ret = $api->api_attachments_form_upload( "." .$extension );
       
       
       $params = [];
       if(isset($ret['key'])){
            $params = [
                'key'=> $ret['key'],
                'acl'=> $ret['acl'],
                'x-amz-algorithm'=> $ret['algorithm'],
                'x-amz-credential'=> $ret['credential'],
                'x-amz-date'=> $ret['date'],
                'x-amz-signature'=> $ret['signature'],
                'policy'=> $ret['policy'],
                'file'=> @fopen( $tmpFilePath,'r' ),   
                //要上传的文件资源
            ];           
       }
       
       $data = $api->send_upload_data(  $params );
       $data['originalName'] = $originalName;
       $data['result'] = 'success';
       if(isset($data['error']) && $data['error']['errorCode'] >0  ){
           header('HTTP/1.1 500 Internal Server Error');
           throw  new \Piwik\Exception\Exception( $originalName, 500);
       }
       return   $data   ;  */
    }
    
}
